<template>
  <view class="admins">
    <view class="header">
      <text class="title">管理员管理</text>
      <button class="btn-add" @click="showAddAdmin = true">添加管理员</button>
    </view>

    <view class="search-bar">
      <input class="search-input" v-model="searchKeyword" placeholder="搜索管理员用户名或邮箱" @input="searchAdmins" />
    </view>

    <view class="admin-list">
      <view v-for="admin in admins" :key="admin.id" class="admin-item">
        <view class="admin-avatar">
          <text class="avatar-text">{{ admin.username ? admin.username.charAt(0).toUpperCase() : 'A' }}</text>
        </view>

        <view class="admin-info">
          <text class="admin-name">{{ admin.username }}</text>
          <text class="admin-email">{{ admin.email || '未设置邮箱' }}</text>
          <text class="admin-role">角色: {{ admin.role }}</text>
          <text class="admin-created">创建时间: {{ formatDate(admin.createdAt) }}</text>
        </view>

        <view class="admin-status">
          <text class="status-badge" :class="admin.status === 1 ? 'status-active' : 'status-inactive'">
            {{ admin.status === 1 ? '正常' : '禁用' }}
          </text>
          <text class="last-login">{{ admin.lastLoginAt ? '最后登录: ' + formatDate(admin.lastLoginAt) : '从未登录' }}</text>
        </view>

        <view class="admin-actions">
          <button class="btn-edit" @click="editAdmin(admin)">编辑</button>
          <button class="btn-toggle" :class="admin.status === 1 ? 'btn-disable' : 'btn-enable'"
            @click="toggleAdminStatus(admin)" v-if="admin.id !== currentAdminId">
            {{ admin.status === 1 ? '禁用' : '启用' }}
          </button>
          <button class="btn-delete" @click="deleteAdmin(admin.id)"
            v-if="admin.id !== currentAdminId && !admin.isSystem">
            删除
          </button>
        </view>
      </view>
    </view>

    <view class="pagination">
      <button class="page-btn" :disabled="currentPage <= 1" @click="loadAdmins(currentPage - 1)">
        上一页
      </button>
      <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
      <button class="page-btn" :disabled="currentPage >= totalPages" @click="loadAdmins(currentPage + 1)">
        下一页
      </button>
    </view>

    <!-- 添加/编辑管理员弹窗 -->
    <view v-if="showAddAdmin || editingAdmin" class="modal-overlay" @click="closeAdminModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ editingAdmin ? '编辑管理员' : '添加管理员' }}</text>
          <text class="modal-close" @click="closeAdminModal">×</text>
        </view>
        <view class="modal-body">
          <view class="form-group">
            <text class="form-label">用户名</text>
            <input class="form-input" v-model="adminForm.username" placeholder="请输入用户名" />
          </view>
          <view class="form-group">
            <text class="form-label">邮箱</text>
            <input class="form-input" v-model="adminForm.email" placeholder="请输入邮箱" />
          </view>
          <view class="form-group" v-if="!editingAdmin">
            <text class="form-label">密码</text>
            <input class="form-input" type="password" v-model="adminForm.password" placeholder="请输入密码" />
          </view>
          <view class="form-group">
            <text class="form-label">角色</text>
            <picker :value="roleIndex" :range="availableRoles" range-key="displayName" @change="onRoleChange">
              <view class="picker-view">{{ getRoleDisplayName(roleIndex) }}</view>
            </picker>
          </view>
          <view class="form-group">
            <text class="form-label">状态</text>
            <picker :value="statusIndex" :range="statusOptions" @change="onStatusChange">
              <view class="picker-view">{{ statusOptions[statusIndex] }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeAdminModal">取消</button>
          <button class="btn-confirm" @click="saveAdmin">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      admins: [],
      searchKeyword: '',
      currentPage: 1,
      totalPages: 1,
      pageSize: 10,
      showAddAdmin: false,
      editingAdmin: null,
      currentAdminId: null,
      adminForm: {
        username: '',
        email: '',
        password: '',
        role: '',
        status: 1
      },
      availableRoles: [],
      roleIndex: 0,
      statusOptions: ['禁用', '正常'],
      statusIndex: 1
    }
  },

  onLoad() {
    this.getCurrentAdmin()
    this.loadAdmins()
    this.loadRoles()
  },

  methods: {
    async getCurrentAdmin() {
      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: 'http://localhost:3000/api/admin/auth/profile',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          this.currentAdminId = res.data.data.id
        }
      } catch (error) {
        console.error('获取当前管理员信息失败:', error)
      }
    },

    async loadAdmins(page = 1) {
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.navigateTo({ url: '/pages/auth/login' })
          return
        }

        const res = await uni.request({
          url: `http://localhost:3000/api/admin/admins?page=${page}&limit=${this.pageSize}&search=${this.searchKeyword}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          this.admins = res.data.data.admins || []
          this.currentPage = res.data.data.currentPage || 1
          this.totalPages = res.data.data.totalPages || 1
        }
      } catch (error) {
        console.error('加载管理员失败:', error)
        uni.showToast({
          title: '加载管理员失败',
          icon: 'none'
        })
      }
    },

    async loadRoles() {
      try {
        const token = uni.getStorageSync('token')
        const res = await uni.request({
          url: 'http://localhost:3000/api/admin/roles',
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (res.data.success) {
          this.availableRoles = res.data.data || []
        }
      } catch (error) {
        console.error('加载角色失败:', error)
      }
    },

    searchAdmins() {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.loadAdmins(1)
      }, 500)
    },

    editAdmin(admin) {
      this.editingAdmin = admin
      this.adminForm = {
        username: admin.username || '',
        email: admin.email || '',
        password: '',
        role: admin.role || '',
        status: admin.status || 1
      }

      this.roleIndex = this.availableRoles.findIndex(role => role.name === this.adminForm.role)
      if (this.roleIndex === -1) this.roleIndex = 0
      this.statusIndex = this.adminForm.status === 1 ? 1 : 0
    },

    async toggleAdminStatus(admin) {
      const action = admin.status === 1 ? '禁用' : '启用'
      uni.showModal({
        title: `确认${action}`,
        content: `确定要${action}管理员 ${admin.username} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const updateRes = await uni.request({
                url: `http://localhost:3000/api/admin/admins/${admin.id}/status`,
                method: 'PUT',
                header: {
                  'Authorization': `Bearer ${token}`,
                  'Content-Type': 'application/json'
                },
                data: {
                  status: admin.status === 1 ? 0 : 1
                }
              })

              if (updateRes.data.success) {
                uni.showToast({ title: `${action}成功` })
                this.loadAdmins(this.currentPage)
              }
            } catch (error) {
              uni.showToast({ title: `${action}失败`, icon: 'none' })
            }
          }
        }
      })
    },

    async deleteAdmin(adminId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个管理员吗？删除后无法恢复。',
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const deleteRes = await uni.request({
                url: `http://localhost:3000/api/admin/admins/${adminId}`,
                method: 'DELETE',
                header: {
                  'Authorization': `Bearer ${token}`
                }
              })

              if (deleteRes.data.success) {
                uni.showToast({ title: '删除成功' })
                this.loadAdmins(this.currentPage)
              }
            } catch (error) {
              uni.showToast({ title: '删除失败', icon: 'none' })
            }
          }
        }
      })
    },

    closeAdminModal() {
      this.showAddAdmin = false
      this.editingAdmin = null
      this.adminForm = {
        username: '',
        email: '',
        password: '',
        role: '',
        status: 1
      }
      this.roleIndex = 0
      this.statusIndex = 1
    },

    async saveAdmin() {
      if (!this.adminForm.username) {
        uni.showToast({ title: '请输入用户名', icon: 'none' })
        return
      }

      if (!this.adminForm.email) {
        uni.showToast({ title: '请输入邮箱', icon: 'none' })
        return
      }

      if (!this.editingAdmin && !this.adminForm.password) {
        uni.showToast({ title: '请输入密码', icon: 'none' })
        return
      }

      if (!this.adminForm.role) {
        uni.showToast({ title: '请选择角色', icon: 'none' })
        return
      }

      try {
        const token = uni.getStorageSync('token')
        const url = this.editingAdmin
          ? `http://localhost:3000/api/admin/admins/${this.editingAdmin.id}`
          : 'http://localhost:3000/api/admin/admins'

        const res = await uni.request({
          url,
          method: this.editingAdmin ? 'PUT' : 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: this.adminForm
        })

        if (res.data.success) {
          uni.showToast({ title: '保存成功' })
          this.closeAdminModal()
          this.loadAdmins(this.currentPage)
        }
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },

    onRoleChange(e) {
      this.roleIndex = e.detail.value
      const selectedRole = this.availableRoles[e.detail.value]
      this.adminForm.role = selectedRole ? selectedRole.name : ''
    },

    getRoleDisplayName(index) {
      const role = this.availableRoles[index]
      return role ? role.displayName : '请选择角色'
    },

    onStatusChange(e) {
      this.statusIndex = e.detail.value
      this.adminForm.status = e.detail.value === 1 ? 1 : 0
    },

    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.admins {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.btn-add {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.search-bar {
  margin-bottom: 30rpx;
}

.search-input {
  width: 100%;
  padding: 20rpx;
  background: white;
  border-radius: 12rpx;
  font-size: 28rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.admin-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.admin-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.admin-item:last-child {
  border-bottom: none;
}

.admin-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #007bff;
  color: white;
}

.avatar-text {
  font-size: 32rpx;
  font-weight: bold;
}

.admin-info {
  flex: 1;
  margin-right: 20rpx;
}

.admin-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.admin-email {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.admin-role,
.admin-created {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.admin-status {
  margin-right: 20rpx;
  text-align: center;
}

.status-badge {
  display: block;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: white;
  margin-bottom: 8rpx;
}

.status-active {
  background-color: #28a745;
}

.status-inactive {
  background-color: #dc3545;
}

.last-login {
  font-size: 20rpx;
  color: #666;
}

.admin-actions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.btn-edit {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.btn-disable {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.btn-enable {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.btn-delete {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30rpx;
  padding: 30rpx;
}

.page-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.page-btn:disabled {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.picker-view {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-confirm {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style>